package com.worldcup.service;

import com.worldcup.common.CommonResult;
import com.worldcup.utils.OssUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author duwan.zq
 * @date 2018/06/13
 */
@Service
public class PhantomJsService {

    private final static Logger logger = LoggerFactory.getLogger(PhantomJsService.class);

    @Value("${phantomJs.exe.file:null}")
    private String phantomJsExeFile;

    @Value("${phantomJs.script.file:null}")
    private String phantomJsScriptFile;


    public String createImage(String html) throws IOException, InterruptedException {
        String uuid = UUID.randomUUID().toString();
        File file = new File("/home/gmj/code/worldcup-back/game-result/" + uuid + ".html");
        FileOutputStream outputStream = new FileOutputStream(file);
        html = "<link href=\"https://worldcup.dmpb.com.cn/game-result/worldcup.css\" type=\"text/css\" rel=\"stylesheet\">" + html;
        byte[] htmlByte = html.getBytes();
        outputStream.write(htmlByte);
        outputStream.flush();

        String htmlUrl = "https://worldcup.dmpb.com.cn/game-result/" + uuid + ".html";
        logger.info("生成html,url = " + htmlUrl);
        String resultImagePath = "/home/gmj/code/worldcup-back/game-result-img/" + uuid + ".png";
        String command = phantomJsExeFile + "  "
            + phantomJsScriptFile + "   "
            + htmlUrl + "   " //你的目标url地址
            + resultImagePath;
        logger.info("command = " + command);
        Process process = Runtime.getRuntime().exec(command);
        int returnValue = process.waitFor();
        logger.info("生成图片,url = " + resultImagePath);
        OssUtils.getOssClient().upload("game-result-img/" + uuid + ".png", new File(resultImagePath));
        logger.info("上传oss " );

        //删除html和图片
        //file.delete();
        new File(resultImagePath).delete();

        return "https://worldcuptemp.oss-cn-beijing.aliyuncs.com/game-result-img/" + uuid + ".png";
    }
}
